package com.ssy.lingxi.transaction.serviceimpl;

import cn.hutool.core.bean.BeanUtil;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.transaction.api.common.OrderConstant;
import com.ssy.lingxi.transaction.api.dto.request.InquiryListDetailsRequest;
import com.ssy.lingxi.transaction.api.dto.request.InquiryListRequest;
import com.ssy.lingxi.transaction.api.dto.response.*;
import com.ssy.lingxi.transaction.api.enums.InquiryExternalStatusEnum;
import com.ssy.lingxi.transaction.entity.Inquiry;
import com.ssy.lingxi.transaction.entity.record.InquiryExternalRecord;
import com.ssy.lingxi.transaction.repository.InquiryExternalRecordRepository;
import com.ssy.lingxi.transaction.repository.InquiryProductRepository;
import com.ssy.lingxi.transaction.repository.InquiryRepository;
import com.ssy.lingxi.transaction.service.IPlatformInquiryService;
import com.ssy.lingxi.workflow.api.feign.ProcessFeign;
import com.ssy.lingxi.workflow.api.model.contant.ProcessEnum;
import com.ssy.lingxi.workflow.api.model.vo.request.ExternalProcessQueryVO;
import com.ssy.lingxi.workflow.api.model.vo.response.SimpleProcessDefVO;
import com.ssy.lingxi.workflow.api.model.vo.response.SimpleTaskVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PlatformInquiryServiceImpl implements IPlatformInquiryService {

    @Resource
    InquiryRepository inquiryRepository;

    @Resource
    InquiryProductRepository inquiryProductRepository;

    @Resource
    InquiryExternalRecordRepository inquiryExternalRecordRepository;

    @Resource
    ProcessFeign processFeign;

    /**
     * 交易中心-商品询价-询价单详情
     */
    @Override
    public Wrapper<InquiryListDetailsResponse> inquiryListDetails(InquiryListDetailsRequest request) {
        InquiryListDetailsResponse inquiryListDetailsResponse=new InquiryListDetailsResponse();
        Inquiry inquiryList = inquiryRepository.findById(request.getId()).orElse(null);
        if(null==inquiryList){
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        BeanUtils.copyProperties(inquiryList,inquiryListDetailsResponse);
        List<InquiryListProductResponse> collect = inquiryProductRepository.findAllByInquiryIdEquals(request.getId()).stream().map(inquiryListProduct -> {
            InquiryListProductResponse inquiryListResponse = new InquiryListProductResponse();
            BeanUtils.copyProperties(inquiryListProduct,inquiryListResponse);
            return inquiryListResponse;
        }).collect(Collectors.toList());
        inquiryListDetailsResponse.setInquiryListProductRequests(collect);
        inquiryListDetailsResponse.setInquiryListMemberName(inquiryList.getCreateMemberName());
        getExternalLog(inquiryListDetailsResponse,  inquiryList.getId());
        inquiryListDetailsResponse.setExternalStateName(InquiryExternalStatusEnum.getName(inquiryListDetailsResponse.getExternalState()));
        return Wrapper.success(inquiryListDetailsResponse);
    }

    /**
     * 交易中心-商品询价-询价单列表查询
     */
    @Override
    public Wrapper<PageData<InquiryListResponse>> inquiryList(InquiryListRequest request, UserLoginCacheDTO sysUser) {
        Pageable page = PageRequest.of(request.getCurrent(), request.getPageSize());
        Page<Inquiry> result = inquiryRepository.findAll(getSpecification(request), page);
        List<InquiryListResponse> inquiryListResponseList = result.getContent().stream().map(inquiry -> {
            InquiryListResponse inquiryListResponse = BeanUtil.copyProperties(inquiry, InquiryListResponse.class);
            inquiryListResponse.setExternalStateName(InquiryExternalStatusEnum.getName(inquiryListResponse.getExternalState()));
            inquiryListResponse.setInquiryListMemberName(inquiry.getCreateMemberName());
            inquiryListResponse.setInquiryListMemberId(inquiry.getCreateMemberId());
            return inquiryListResponse;
        }).collect(Collectors.toList());
        return Wrapper.success(new PageData<>(result.getTotalElements(), inquiryListResponseList));
    }

    /**
     * 构建查询条件
     */
    private Specification<Inquiry> getSpecification(InquiryListRequest request) {
        return (Specification<Inquiry>) (root, query, criteriaBuilder) -> {
            Predicate finalConditions = criteriaBuilder.conjunction();

            String details = request.getDetails();
            String inquiryListNo = request.getInquiryListNo();
            String inquiryListMemberName = request.getInquiryListMemberName();
            String memberName = request.getMemberName();
            Long startDocumentsTime = request.getStartDocumentsTime();
            Long endDocumentsTime = request.getEndDocumentsTime();
            Integer externalState = request.getExternalState();
            Integer interiorState = request.getInteriorState();

            //描述
            if(StringUtils.isNotEmpty(details)){
                Predicate predicate = criteriaBuilder.like(root.get("details"), "%" + details + "%");
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }
            //询价单号
            if(StringUtils.isNotEmpty(inquiryListNo)){
                Predicate predicate = criteriaBuilder.like(root.get("inquiryListNo"), "%" + inquiryListNo + "%");
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }
            //询价会员名称
            if(StringUtils.isNotEmpty(inquiryListMemberName)){
                Predicate predicate = criteriaBuilder.like(root.get("createMemberName"), "%" + inquiryListMemberName + "%");
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }
            //报价会员名称
            if(StringUtils.isNotEmpty(memberName)){
                Predicate predicate = criteriaBuilder.like(root.get("memberName"), "%" + memberName + "%");
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }
            //开始单据时间
            if(startDocumentsTime != null && startDocumentsTime > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.ge(root.get("voucherTime"), startDocumentsTime));
            }
            //结束单据时间
            if(endDocumentsTime != null && endDocumentsTime > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.le(root.get("voucherTime"), endDocumentsTime));
            }
            //状态
            if (externalState != null && externalState > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("externalState"), externalState));
            }
            if (interiorState != null && interiorState > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("interiorState"), interiorState));
            }

            //排序
            Order createTimeOrder = criteriaBuilder.desc(root.get("id"));

            return query.orderBy(createTimeOrder).where(finalConditions).getRestriction();
        };
    }

//    /**
//     * sql拼接
//     *
//     * @author wrc
//     * @date 2020/7/31
//     */
//    private String sqlJointList(InquiryListRequest request, String condition) {
//        StringBuilder sbList = new StringBuilder();
//        sbList.append("SELECT  rf.member_name as memberName,rf.create_member_name as inquiryListMemberName,rf.inquiry_list_no as inquiryListNo,rf.id as id,rf.details as details,rf.delivery_time as deliveryTime,rf.quotation_as_time as quotationAsTime,rf.voucher_time as voucherTime,rf.external_state as externalState,rf.interior_state as interiorState " +
//                "FROM trade_inquiry rf  ");
//        sbList.append(condition);
//        sbList.append(" order by  rf.id desc ");
//        sbList.append(" limit ");
//        sbList.append(request.getPageSize());
//        sbList.append(" OFFSET ");
//        sbList.append(request.getCurrent() * request.getPageSize());
//        return sbList.toString();
//    }
//
//    /**
//     * sql拼接
//     *
//     * @author wrc
//     * @date 2020/7/31
//     */
//    private String sqlJointCount(String condition) {
//        StringBuilder sbCount = new StringBuilder();
//        sbCount.append("SELECT count(DISTINCT rf.id) FROM trade_inquiry rf  ");
//        sbCount.append(condition);
//        return sbCount.toString();
//    }

//    /**
//     * sql拼接
//     *
//     * @P queryType 查询类型：1.报价单查询 2. 待新增报价单查询 3.待审核报价单（一级） 4.待审核报价单（二级） 5.待提交报价单
//     * @author wrc
//     * @date 2020/7/31
//     */
//    private String sqlJointCondition(InquiryListRequest request) {
//        StringBuilder sbCondition = new StringBuilder();
//        sbCondition.append(" where 1=1 ");
//        if (null != request && null != request.getDetails() && !request.getDetails().isEmpty()) {
//            sbCondition.append(" AND  rf.details like  '%");
//            sbCondition.append(request.getDetails());
//            sbCondition.append("%'");
//        }
//        if (null != request && null != request.getStartDocumentsTime() && null != request.getEndDocumentsTime()) {
//            sbCondition.append(" AND  rf.voucher_time BETWEEN ");
//            sbCondition.append(request.getStartDocumentsTime());
//            sbCondition.append(" and ");
//            sbCondition.append(request.getEndDocumentsTime());
//        }
//        if (null != request.getExternalState()) {
//            sbCondition.append(" AND  rf.external_state = ");
//            sbCondition.append(request.getExternalState());
//        }
//        if (null != request.getInteriorState()) {
//            sbCondition.append(" AND  rf.interior_state = ");
//            sbCondition.append(request.getInteriorState());
//        }
//        if(null!=request.getInquiryListMemberName()&&!request.getInquiryListMemberName().isEmpty()){
//            sbCondition.append(" AND  rf.create_member_name like  '%");
//            sbCondition.append(request.getInquiryListMemberName());
//            sbCondition.append("%' ");
//        }
//        if(null!=request.getMemberName()&&!request.getMemberName().isEmpty()){
//            sbCondition.append(" AND  rf.member_name like  '%");
//            sbCondition.append(request.getMemberName());
//            sbCondition.append("%' ");
//        }
//
//        if(null!=request.getInquiryListNo()&&!request.getInquiryListNo().isEmpty()){
//            sbCondition.append(" AND  rf.inquiry_list_no like  '%");
//            sbCondition.append(request.getInquiryListNo());
//            sbCondition.append("%' ");
//        }
//        return sbCondition.toString();
//    }

    /**
     * 获取询价单外部操作流程
     */
    private void getExternalLog(InquiryListDetailsResponse response, Long id) {
        List<InquiryExternalRecord> externalRequisitionForms = inquiryExternalRecordRepository.findAllByInquiryListIdEquals(id);
        //查询外部流转
        ExternalProcessQueryVO taskStepVO = new ExternalProcessQueryVO();
        taskStepVO.setRoleId(response.getCreateRoleId());
        taskStepVO.setProcessKey(ProcessEnum.TRADE_INQUIRY_EXTERNAL.getProcessKey());
        Wrapper<SimpleProcessDefVO> wrapper = processFeign.findSimpleExternalTaskDefinitions(taskStepVO);
        List<LogStateResponse> externalList = new ArrayList<>();
        if (ResponseCode.SUCCESS.getCode() != wrapper.getCode()) {
            throw new RuntimeException(wrapper.getMessage());
        }
        List<SimpleTaskVO> data = wrapper.getData().getTasks();
        data.forEach(taskStepQueryVO -> {
            LogStateResponse quotationState = new LogStateResponse();
            if (!CollectionUtils.isEmpty(externalRequisitionForms)) {
                Integer state = externalRequisitionForms.get(externalRequisitionForms.size() - 1).getState();
                quotationState.setIsExecute(state >= taskStepQueryVO.getTaskStep() ? OrderConstant.State.START : OrderConstant.State.STOP);
            } else {
                quotationState.setIsExecute(OrderConstant.State.STOP);
            }
            quotationState.setOperationalProcess(taskStepQueryVO.getTaskName());
            quotationState.setRoleName(taskStepQueryVO.getRoleName());
            quotationState.setState(taskStepQueryVO.getTaskStep());
            externalList.add(quotationState);
        });
        if(!CollectionUtils.isEmpty(externalList)){
            externalList.get(0).setIsExecute(OrderConstant.State.START );
        }
        response.setExternalInquiryListStateResponses(externalList);
        if (CollectionUtils.isEmpty(externalRequisitionForms)) {
            return;
        }
        //查询外部和内部工作流记录
        List<ExternalInquiryListLogResponse> externalInquiryListLogResponseList = externalRequisitionForms.stream().map(externalInquiryListLog -> {
            ExternalInquiryListLogResponse externalInquiryListLogResponse = new ExternalInquiryListLogResponse();
            BeanUtils.copyProperties(externalInquiryListLog, externalInquiryListLogResponse);
            externalInquiryListLogResponse.setStateName(InquiryExternalStatusEnum.getName(externalInquiryListLogResponse.getState()));
            return externalInquiryListLogResponse;
        }).collect(Collectors.toList());
        response.setExternalInquiryListLogResponses(externalInquiryListLogResponseList);

    }
}
